package com.maixy.studyonlineapi.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.maixy.studyonlineapi.entity.Media;
import com.maixy.studyonlineapi.entity.User;
import com.maixy.studyonlineapi.mapper.MediaMapper;
import com.maixy.studyonlineapi.utils.DataTypeUtil;
import com.maixy.studyonlineapi.view.MediaView;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName MediaService
 * @Description TODO
 * @Date 2020/11/28 21:36
 * @Author maixy
 */
@Service
public class MediaService extends BaseMPlusService<Media, Long>{

    private MediaMapper mediaMapper;

    @Resource
    private UserService userService;

    protected MediaService(MediaMapper mediaMapper) {
        super(Media.class, mediaMapper);
        this.mediaMapper = mediaMapper;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public MediaView saveMedia(Integer mediaType, String mediaUrl) {
        Media media = new Media();
        media.setHasDelete(false);
        media.setCreateTime(System.currentTimeMillis());
        media.setMediaType(mediaType);
        media.setMediaUrl(mediaUrl);
        create(media);
        return convert(media);
    }

    public MediaView convert(Media media) {
        MediaView view = new MediaView();
        view.setMediaId(DataTypeUtil.getStr(media.getId()));
        view.setMediaType(media.getMediaType());
        view.setMediaUrl(media.getMediaUrl());
        return view;
    }

    /**
     * 用户登录前获得头像
     *
     * @param userName 用户名
     * @return com.maixy.studyonlineapi.view.MediaView
     */
    public MediaView loginAvatar(String userName) {
        User user = userService.findUserByUserName(userName);
        if ( null != user) {
            Media media = findById(user.getAvatarId());
            if (null != media && !media.getHasDelete()) {
                return convert(media);
            }
        }
        return null;
    }

    public List<Media> findMediaByType(Integer mediaType) {
        return this.mediaMapper.selectList(new QueryWrapper<Media>()
                .lambda()
                .eq(Media::getHasDelete, false)
                .eq(Media::getMediaType, 1)
                .last("limit 5"));
    }
}
